import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 循环屏障
public class CyclicBarrierDemo1 {
    public static void main(String[] args) {
        // 循环屏障
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                System.out.println("计数器为 0 了");
            }
        });
        // 创建线程池
        ExecutorService service = Executors.newFixedThreadPool(4);

        for (int i = 0; i < 4; i++) {
            int finalI = i;
            service.submit(() -> {
                Thread currThread = Thread.currentThread();
                System.out.println("执行线程：" + currThread.getName());
                try {
                    Thread.sleep(500 * finalI);
                    cyclicBarrier.await(); // 执行阻塞等待（直到循环屏障的计数器为0的时候，再执行后面的代码）
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("线程执行完成:"+currThread.getName());
            });
        }

    }
}
